package summer.codegenerator.dto;

import java.util.LinkedList;
import java.util.List;

import org.hibernate.NullPrecedence;
import org.hibernate.criterion.Order;
import org.springframework.util.CollectionUtils;

/**
 * 排序模型
 * 
 * @author 蒋振
 * @since 2019年7月4日 上午9:14:27
 */
public class OrderModel {

	private boolean ascending;

	private boolean ignoreCase;

	private String propertyName;

	private String nullPrecedence;

	public boolean isAscending() {
		return ascending;
	}

	public void setAscending(boolean ascending) {
		this.ascending = ascending;
	}

	public boolean isIgnoreCase() {
		return ignoreCase;
	}

	public void setIgnoreCase(boolean ignoreCase) {
		this.ignoreCase = ignoreCase;
	}

	public String getPropertyName() {
		return propertyName;
	}

	public void setPropertyName(String propertyName) {
		this.propertyName = propertyName;
	}

	public String getNullPrecedence() {
		return nullPrecedence;
	}

	public void setNullPrecedence(String nullPrecedence) {
		this.nullPrecedence = nullPrecedence;
	}

	public Order genOrder() {
		Order order = this.ascending ? Order.asc(this.propertyName) : Order.desc(this.propertyName);

		// 默认依赖数据库规则
		NullPrecedence nullPrecedence = NullPrecedence.parse(this.nullPrecedence, NullPrecedence.NONE);
		order.nulls(nullPrecedence);

		// 不区分大小写
		if (this.ignoreCase) {
			order.ignoreCase();
		}

		return order;
	}

	public static List<Order> genOrders(List<OrderModel> dtos) {
		if (CollectionUtils.isEmpty(dtos)) {
			return null;
		}
		List<Order> orders = new LinkedList<Order>();
		for (OrderModel dto : dtos) {
			orders.add(dto.genOrder());
		}
		return orders;
	}
}
